export default {
  // 为当前模块开启命名空间
  namespaced: true,
  state: () => ({
    // 购物车模块所需的数据的数组
    cart: JSON.parse(uni.getStorageSync('cart')||'[]'),
  }),
  mutations: {
    // 加入购物车
      addToCart(state,goods){
        const findResult=state.cart.find((x)=>x.goods_id===goods.goods_id)
        if(!findResult){
          state.cart.push(goods)
        }else{
          findResult.goods_count++
          }
          this.commit('m_cart/saveToStorage')
      },
      saveToStorage(state){
        uni.setStorageSync('cart',JSON.stringify(state.cart))
      },
      // 商品选中状态
      updateGoodsState(state,goods){
        const findResult = state.cart.find(x=>x.goods_id===goods.goods_id)
        if(findResult){
          findResult.goods_state=goods.goods_state
        }
        this.commit('m_cart/saveToStorage')
      },
      // 商品数量
      updateGoodsCount(state,goods){
        const findResult = state.cart.find(x=>x.goods_id===goods.goods_id)
        if(findResult){
          findResult.goods_count=goods.goods_count
        }
        this.commit('m_cart/saveToStorage')
      },
      // 删除购物车内的商品
      delCartGoods(state,id){
        state.cart= state.cart.filter(x=>x.goods_id!==id)
        this.commit('m_cart/saveToStorage')
      },
      // 是否全选
      updateAllCheck(state,newState){
        state.cart.forEach(x=>x.goods_state=newState)
        this.commit('m_cart/saveToStorage')
      }
  },
  getters: {
    total(state){
      let num=0
      state.cart.forEach(goods => num += goods.goods_count)
      return num
    },
    checkedCount(state){
      return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
    },
    checkedAllGoods(state){
      return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
      }
  }
}
